package com.ybb.job;


import com.ybb.account.service.MerchantAccountService;
import com.ybb.common.configuration.OrderConfiguration;
import com.ybb.common.util.DateUtils;
import com.ybb.job.service.JobLockService;
import com.ybb.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.*;

@Component
public class ScheduledTasks {
    private static final String NODE_ID = UUID.randomUUID().toString();

    private boolean enabled = false;

    @Autowired
    private JobLockService lockService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private MerchantAccountService accountService;

    @Autowired
    private OrderConfiguration orderConfiguration;

    @Scheduled(fixedRate = 3000) // 每隔30秒执行一次
    public void keepLock() {
        Integer count = lockService.getLock(NODE_ID, "settle_scheduler");
        if (count > 0) {
            enabled = true;
            System.out.println("我是主！");
        } else {
            enabled = false;
            System.out.println("我是备");
        }
    }

    @Scheduled(cron = "0 0 1 * * *") // 每天1点执行一次
    public void settle() {
        if (enabled) {
            System.out.println("开始执行结算....");
            LocalDateTime todayBegin = DateUtils.todayBegin();
            LocalDateTime yesterdayBegin = DateUtils.dateMinusDay(todayBegin, 1);

            Date todayBeginDate = DateUtils.localDateTime2Date(todayBegin);
            Date yesterdayBeginDate = DateUtils.localDateTime2Date(yesterdayBegin);
            //商户昨天所有已支付订单的金额之和
            Map<String,Double> amountChangeInOrder = orderService.orderAmount(yesterdayBeginDate, todayBeginDate);
            Map<String,Double> amountChangeInAccount = accountService.settleMerchantBalance(yesterdayBeginDate, todayBeginDate);

            Set<String> diff = new HashSet<>(amountChangeInAccount.keySet());
            diff.removeAll(amountChangeInOrder.keySet()); //amountChangeInAccount-amountChangeInOrder的差异

            if(diff.size()>0){
                System.out.println("以下商户结算数据不一致："+diff);
            }
            for( Map.Entry<String,Double> entry:amountChangeInOrder.entrySet()){ //amountChangeInOrder-amountChangeInAccount的差异
                if(amountChangeInAccount.get(entry.getKey()) != entry.getValue()){
                    System.out.println("商户"+entry.getKey()+" 金额对不上。");
                }
            }
        }
    }

    @Scheduled(fixedRate = 300000) // 每5分钟循环一次
    public void checkTimeoutOrder() {
        if (enabled) {
            Integer validateDays = orderConfiguration.getValidateDays();
            Date cancelTime = DateUtils.localDateTime2Date(DateUtils.dateMinusDay(LocalDateTime.now(), validateDays));
            List<Integer> orderIds = orderService.getTimeOutOrders(cancelTime, OrderService.ORDER_STATUS_UNPAY);
            for (Integer orderId : orderIds) {
                orderService.cancelOrder(orderId);
            }
        }
    }
}
